package ThreadPool;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer_Thread extends Thread{
    public static int clientCount;
    private static ServerSocket ss = null;
    private  ExecutorService threadpool = null;
       public TCPServer_Thread(){
           try {
               ss =  new ServerSocket(9999);
               int n = Runtime.getRuntime().availableProcessors();
               threadpool = Executors.newFixedThreadPool(2*n);
           }
           catch (IOException e) {
               System.out.println("绑定客户端失败：" + e.getMessage() );
           }
       }
    public static void main(String[] args) throws IOException {
       TCPServer_Thread tcpServer_thread = new TCPServer_Thread();
       tcpServer_thread.start();
    }

    @Override
    public void run() {
        try {
            while (true)
            {
            Socket s = ss.accept();
             clientCount++;
            socketThread socketThread = new socketThread(s , clientCount);
            //socketThread.start();//交给线程池
                threadpool.execute(socketThread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            }
        }
    }

